<?php
/**
 * User: Mykola B.
 * Date: 3/4/13
 * Time: 7:45 AM
 */
class Time
{
    /**
     * @var int
     */
    public $seconds = 0;

    /**
     * @param string $timeString in format H:I:S
     */
    public function __construct($timeString = null) {
        if (!is_null($timeString)) {
            $timeParts = explode(':', $timeString, 3);
            list($hours, $minutes, $seconds) = array_map('intval', $timeParts);
            $this->seconds = $this->toSeconds($hours, $minutes, $seconds);
        }
    }

    /**
     * @param int $s
     * @return Time
     */
    public static function fromSeconds($s = 0) {
        $time = new Time();
        $time->seconds = $s;
        return $time;
    }

    /**
     * @param int $h
     * @param int $i
     * @param int $s
     */
    public function toSeconds($h = 0, $i = 0, $s = 0) {
        $i += abs($h * 60);
        $s += $i * 60;
        return $h < 0 ? -$s : $s;
    }

    /**
     * @param int $s
     */
    public function toHIS($s = 0) {
        $isNegative = $s < 0;
        $s = abs($s);
        $i = intval($s / 60);
        $s = $s % 60;
        $h = intval($i / 60);
        $i = $i % 60;
        return array($isNegative ? -$h : $h, $i, $s);
    }

    /**
     * @param Time $other
     * @return Time
     */
    public function add(Time $other) {
        return Time::fromSeconds($this->seconds + $other->seconds);
    }

    public function sub(Time $other) {
        return Time::fromSeconds($this->seconds - $other->seconds);
    }

    public function lt(Time $other) {
        return $this->seconds < $other->seconds;
    }

    public function __toString() {
        list($h, $i, $s) = $this->toHIS($this->seconds);
        return sprintf('%02d:%02d:%02d', $h, $i, $s);
    }
}
